<template>
  <a-spin :spinning="confirmLoading">
    <a-tabs defaultActiveKey="1" :activeKey.sync="activeKey" @change="tabsChange">
      <a-tab-pane tab="合同评审表" key="1">
        <j-form-container>
          <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
            <a-row>
              <a-col :span="6">
                <a-form-model-item label="评审表编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
                  <a-input v-model="model.code" placeholder="请输入评审表编号" :disabled="formDisabled"></a-input>
                </a-form-model-item>
              </a-col>

              <a-col :span="6">
                <a-form-model-item
                  label="销售订单号"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="schedulingNumber"
                >
                  <a-input
                    v-model="model.schedulingNumber"
                    placeholder="请输入销售订单号"
                    :disabled="formDisabled && starterDisabled"
                  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="2">
                <a-button type="primary" icon="" size="small" @click="getSchedulingNumber">自动获取 </a-button>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="是否确认版样" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isPattern">
                  <j-dict-select-tag
                    type="list"
                    :disabled="formDisabled"
                    v-model="model.isPattern"
                    dictCode="yes_no"
                    placeholder="请选择是否确认版样"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="审批流程" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="flowFlag">
                  <j-dict-select-tag
                    type="list"
                    :disabled="formDisabled"
                    v-model="model.flowFlag"
                    dictCode="contract_review_flow"
                    placeholder="请选择审批流程"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="定金" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deposit">
                  <a-input-number
                    v-model="model.deposit"
                    placeholder="请输入定金"
                    :disabled="formDisabled"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item
                  label="已到预付款"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="advancePayment"
                >
                  <a-input
                    v-model="model.advancePayment"
                    :disabled="formDisabled"
                    placeholder="请输入已到预付款"
                  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="定货日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractTime">
                  <a-input v-model="model.contractTime" disabled placeholder="请输入定货日期"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item
                  label="合同评审说明"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="contractCode"
                >
                  <a-input v-model="model.contractCode" disabled placeholder="请输入合同评审说明"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="客户名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerId">
                  <j-dict-select-tag
                    type="list"
                    disabled
                    v-model="model.customerId"
                    dictCode="erp_customer,name,id"
                    placeholder="请选择客户"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="客户类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customer">
                  <a-input v-model="model.customer" disabled placeholder="请输入客户类型"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="订货数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="weight">
                  <a-input-number v-model="model.weight" disabled placeholder="请输入重量" style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="重量单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="weightUnit">
                  <j-dict-select-tag
                    type="list"
                    disabled
                    v-model="model.weightUnit"
                    dictCode="zl_unit"
                    placeholder="请选择重量单位"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="币种" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="currency">
                  <j-dict-select-tag
                    type="list"
                    :disabled="formDisabled"
                    @change="changeCurrency"
                    v-model="model.currency"
                    dictCode="currency"
                    placeholder="请选择币种"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="付款方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="payMethod">
                  <a-input v-model="model.payMethod" disabled placeholder="请输入付款方式"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="交货期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deliveryTime">
                  <a-input v-model="model.deliveryTime" disabled placeholder="请输入交货期"></a-input>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-model-item label="备注" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="remark">
                  <a-textarea
                    v-model="model.remark"
                    :disabled="formDisabled"
                    :rows="10"
                    allow-clear
                    showCount
                  ></a-textarea>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="打码生产备注"
                  :labelCol="labelCol2"
                  :wrapperCol="wrapperCol2"
                  prop="productionRemark"
                >
                  <a-textarea
                    v-model="model.productionRemark"
                    :disabled="formDisabled"
                    :rows="10"
                    allow-clear
                    showCount
                  ></a-textarea>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <h4>附件列表</h4>
                <j-vxe-table
                  keep-source
                  :ref="refKeys[0]"
                  :loading="bussContractReviewDesFilesTable.loading"
                  :columns="bussContractReviewDesFilesTable.columns"
                  :dataSource="bussContractReviewDesFilesTable.dataSource"
                  :maxHeight="300"
                  :disabled="true"
                  :rowNumber="true"
                  :rowSelection="true"
                  :toolbar="true"
                >
                  <template v-slot:action="{ row }">
                    <a @click="handlePreviewReviewDesFiles(row)">预览</a>
                  </template>
                </j-vxe-table>
              </a-col>
            </a-row>
          </a-form-model>
        </j-form-container>
      </a-tab-pane>

      <a-tab-pane tab="产品及BOM" key="2" forceRender>
        <j-form-container>
          <a-form-model ref="formProduct" :model="model" :rules="validatorRules" slot="detail">
            <a-row :span="24">
              <a-col :span="3">
                <a-form-model-item label="是否保密" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isSecrecy">
                  <j-dict-select-tag
                    type="list"
                    :disabled="formDisabled"
                    v-model="model.isSecrecy"
                    dictCode="yes_no"
                    placeholder="请输入是否保密"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="损耗率(%)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="lossRate">
                  <a-input-number
                    v-model="model.lossRate"
                    placeholder="请输入损耗率(%)"
                    style="width: 100%"
                    :disabled="formDisabled"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="增加费用" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isIncrease">
                  <j-dict-select-tag
                    type="list"
                    :disabled="formDisabled && formularEditDisabled"
                    v-model="model.isIncrease"
                    dictCode="yes_no"
                    placeholder="请选择是否增加费用"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="9">
                <a-form-model-item
                  label="视比重/粘度(中间值/目标值)"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="proportion"
                >
                  <a-input-number
                    v-model="model.proportion"
                    :disabled="formDisabled && formularConDisabled && formularEditDisabled"
                    placeholder="请输入视比重/粘度(中间值/目标值)"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <!-- 子表单区域 -->
            <a-row :gutter="8" style="margin: 4px">
              <a-col :span="12" title="产品信息">
                <a-card class="mycard">
                  <a-col :span="24">
                    <a-row :gutter="10">
                      <a-col :span="3">
                        <a-form-model-item>
                          <a-button type="primary" icon="" size="small" @click="addGoods"> 新增产品 </a-button>
                        </a-form-model-item>
                      </a-col>
                      <a-col :span="12">
                        <a-form-model-item
                          label="辅数量合计"
                          :labelCol="labelCol"
                          :wrapperCol="wrapperCol"
                          prop="totalProductAmount"
                        >
                          <a-input v-model="model.totalProductAmount" disabled placeholder="合计" style="width: 100%" />
                        </a-form-model-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-model-item label="订货数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="weight">
                          <a-input-number v-model="model.weight" disabled placeholder="请输入重量" />
                        </a-form-model-item>
                      </a-col>
                    </a-row>
                    <erp-category-goods-list-modal
                      ref="selectGoodsList"
                      :modalWidth="modalWidth"
                      :category="1"
                      @goodsOk="goodsOk"
                      checkval="checkbox"
                    >
                    </erp-category-goods-list-modal>
                  </a-col>
                  <a-col :span="24">
                    <!-- 表格 -->
                    <a-table
                      class="mytable"
                      bordered
                      :scroll="{ x: 650, y: 'calc(100vh-350px)' }"
                      :data-source="model.erpGoodsPackageList"
                      :columns="goodsColumns"
                      :rowKey="(record) => record.rowKey"
                      :selected="onSelectChange"
                      :row-selection="{ type: type, selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
                      :pagination="false"
                    >
                      <template slot="number" slot-scope="text, record">
                        <edit-number-cell-2
                          :text="text"
                          :disabled="productDisabled"
                          @change="onCellChange(record, 'number', $event)"
                        ></edit-number-cell-2>
                      </template>
                      <template slot="isProduction" slot-scope="text, record">
                        <a-select
                          :disabled="formDisabled"
                          :value="text"
                          @change="onCellChange(record, 'isProduction', $event)"
                        >
                          <a-select-option
                            v-for="item in openDictOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          >
                            {{ item.label }}
                          </a-select-option>
                        </a-select>
                      </template>
                      <template slot="mainQuantity" slot-scope="text, record">
                        <edit-number-cell-2
                          :text="text"
                          :disabled="formDisabled"
                          @change="onMainQuantityCellChange(record, 'mainQuantity', $event)"
                        ></edit-number-cell-2>
                      </template>
                      <template slot="meUnit" slot-scope="text">
                        <span>{{ unitDictOptions[text] }}</span>
                      </template>
                      <template slot="auUnit" slot-scope="text">
                        <span>{{ zlunitDictOptions[text] }}</span>
                      </template>
                      <template slot="operation" slot-scope="text, record">
                        <a-popconfirm title="确认删除?" @confirm="() => onDelete(record.goodsId)">
                          <a href="javascript:;">删除</a>
                        </a-popconfirm>
                      </template>
                    </a-table>
                  </a-col>
                </a-card>
              </a-col>
              <a-col :span="12" title="BOM信息">
                <a-card class="mycard">
                  <a-row :gutter="10">
                    <a-col :span="2">
                      <h4>BOM信息</h4>
                    </a-col>
                    <a-col :span="2">
                      <a-button
                        :disabled="formDisabled && formularConDisabled"
                        type="primary"
                        icon=""
                        size="small"
                        @click="conFormular"
                        >关联BOM</a-button
                      >
                      <erp-goods-formular-con-modal @formularOk="formularOk" ref="formularCon" />
                    </a-col>
                  </a-row>

                  <a-table
                    ref="formularTable"
                    class="mytable"
                    bordered
                    :data-source="formularDetailList"
                    tableLayout="fixed"
                    :columns="materialColumns"
                    :rowKey="(record) => record.rowNo"
                    :scroll="{ x: 650, y: 'calc(100vh-350px)' }"
                    :pagination="false"
                  >
                    <template slot="formularRatio" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="formDisabled && formularConDisabled && formularEditDisabled"
                        :text="text"
                        @change="onFormularCellChange(record, 'formula', $event)"
                      />
                    </template>
                    <template slot="taxPrice" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="formDisabled && purchaseDisabled"
                        :text="text"
                        @change="onFormularCellChange(record, 'taxPrice', $event)"
                      />
                    </template>
                  </a-table>
                </a-card>
              </a-col>
            </a-row>
            <a-row :gutter="8" style="margin: 4px">
              <a-col :span="24" title="包材信息">
                <a-card class="mycard">
                  <a-row :gutter="10">
                    <a-col :span="2">
                      <h4>包材信息</h4>
                    </a-col>
                    <a-col :span="2">
                      <a-button type="primary" icon="" size="small" @click="addPackage"> 新增包材 </a-button>
                      <erp-category-goods-list-modal
                        ref="selectPackageList"
                        :modalWidth="modalWidth"
                        :category="2"
                        @goodsOk="packageOk"
                        checkval="checkbox"
                      >
                      </erp-category-goods-list-modal>
                    </a-col>
                  </a-row>
                  <a-col :span="24">
                    <j-vxe-table
                      keep-source
                      bordered
                      :ref="refKeys[2]"
                      :dataSource="model.packageList"
                      :columns="packageColumns"
                      :disabled="formDisabled && packageDisabled"
                      class="bold-border"
                    >
                      <template v-slot:action="{ row }">
                        <a v-if="row.patternFile" @click="handlePreviewFile(row)">查看版样</a>
                      </template>
                    </j-vxe-table>
                  </a-col>
                </a-card>
              </a-col>
            </a-row>
            <a-row :gutter="8" style="margin: 4px">
              <a-col :span="24">
                <a-card class="mycard">
                  <a-row :span="24">
                    <a-col :span="12">
                      <a-form-model-item
                        label="配方要求"
                        :labelCol="labelCol2"
                        :wrapperCol="wrapperCol2"
                        prop="formulaReq"
                      >
                        <!--                <j-editor v-model="model.formulaReq"   disabled/>-->
                        <a-textarea v-model="model.formulaReq" :rows="5" allow-clear showCount disabled></a-textarea>
                      </a-form-model-item>
                    </a-col>
                    <a-col :span="12">
                      <a-form-model-item
                        label="包装要求"
                        :labelCol="labelCol2"
                        :wrapperCol="wrapperCol2"
                        prop="packReq"
                      >
                        <!--                <j-editor v-model="model.packReq" disabled/>-->
                        <a-textarea v-model="model.packReq" :rows="5" allow-clear showCount disabled></a-textarea>
                      </a-form-model-item>
                    </a-col>
                  </a-row>
                </a-card>
              </a-col>
            </a-row>
          </a-form-model>
        </j-form-container>
      </a-tab-pane>
      <a-tab-pane tab="业务报价单" key="3" forceRender>
        <buss-out-let-quote-form
          @my-event="getMyEvent"
          ref="outletquote"
          :dataId="model.id"
          :disabled="formDisabled"
          :currency="model.currency"
        ></buss-out-let-quote-form>
      </a-tab-pane>
      <a-tab-pane tab="修改履历" :key="4" :forceRender="true">
        <a-card :bordered="false">
          <tsl-history dataTable="buss_contract_requirement_review" :dataId="model.id"></tsl-history>
        </a-card>
      </a-tab-pane>
    </a-tabs>
    <goods-formula-modal ref="selectFormulaList" :modalWidth="modalWidth" @goodsOk="formulasOk"> </goods-formula-modal>
    <!-- <div class="drawer-bootom-button" v-show="!disableSubmit">
      <a-button @click="submitForm" type="primary" :loading="confirmLoading">提交</a-button>
    </div> -->
  </a-spin>
</template>

<script>
import { httpAction, getAction, postAction, deleteAction, getFileAccessHttpUrl } from '@/api/manage'
import { validateDuplicateValue, randomUUID } from '@/utils/util'
import ErpCategoryGoodsListModal from '@comp/base/modal/ErpCategoryGoodsListModal'
import EditableCell2 from '@comp/table/EditableCell2'
import BussOutLetQuoteForm from '../modules/BussOutLetQuoteForm'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import GoodsFormulaModal from '@comp/base/modal/GoodsFormulaModal'
import { Base64 } from 'js-base64'
import store from '@/store'
import TslHistory from '@comp/tsl/TslHistory.vue'
import moment from 'dayjs'
import { FilePreview } from '@/utils/tslCommon'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import EditNumberCell2 from '../../../../components/table/EditNumberCell2.vue'
import ErpGoodsFormularConModal from '../../../../components/tsl/modules/ErpGoodsFormularConModal.vue'

export default {
  name: 'BussContractRequirementReviewForm',
  mixins: [JVxeTableModelMixin],
  components: {
    TslHistory,
    ErpCategoryGoodsListModal,
    EditableCell2,
    BussOutLetQuoteForm,
    EditNumberCell2,
    GoodsFormulaModal,
    ErpGoodsFormularConModal,
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    /*流程自定义表单数据*/
    customFormData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false,
    },
  },
  data() {
    return {
      disableSubmit: true,
      starterDisabled: true, //业务员最后修改
      productDisabled: true, //修改产品信息
      formularConDisabled: true, //配方关联
      formularEditDisabled: true, //配方修改
      qualityCheckDisabled: true, //质量
      packageDisabled: true, //包材报价
      purchaseDisabled: true, //采购确认原料单价
      financeDisabled: true, //财务可修改报价，确认是否符合销售政策
      tax: 1.13,
      isAdd: false,
      packageTypeOptions: [],
      showPatternFlag: false,
      isTotalAmountOk: false,
      // 合同评审说明关联文件
      bussContractReviewDesFilesTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '附件',
            key: 'filePath',
            type: JVXETypes.file,
            token: true,
            responseName: 'message',
            width: '200px',
            placeholder: '请选择文件',
            defaultValue: '',
          },
          {
            title: '附件说明',
            key: 'fileDesc',
            type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '100px',
            align: 'center',
            slotName: 'action',
          },
        ],
      },
      refKeys: ['bussContractReviewDesFiles', 'history', 'goodsPackageList'],
      procSelectRows: [],
      formularDetailList: [],
      //存储用作修改是否生产时获取对应数据
      erpPackageListTmp: [],
      contract: {},
      activeKey: '1',
      modalWidth: 1250,
      category: '',
      goodsId: '',
      packageId: '',
      materialId: '',
      selectedProduct: {},
      model: {
        id: '',
        desId: '',
        erpGoodsPackageList: [],
        reviewGoodsFomularList: [],
        packageList: [],
        contractCode: '',
        customerId: '',
        customer: '',
        weight: '',
        weightUnit: '',
        payMethod: '',
        deliveryTime: '',
        contractTime: '',
        formulaReq: '',
        packReq: '',
      },
      tabs: {
        activeKey: 1,
      },
      selectedRowKeys: [],
      type: 'radio',
      // 选中行
      selectedRows: [],
      goodsColumns: [
        {
          title: '产品名称',
          dataIndex: 'packageName',
          fixed: 'left',
          width: 120,
        },
        {
          title: '产品编号',
          dataIndex: 'packageCode',
          width: 120,
        },
        {
          title: '规格型号',
          dataIndex: 'noneSpec',
          width: 100,
        },
        {
          title: '是否生产',
          dataIndex: 'isProduction',
          scopedSlots: { customRender: 'isProduction' },
          width: 100,
        },
        {
          title: '包装方式',
          dataIndex: 'packageType',
          width: 120,
        },
        {
          title: '主数量',
          dataIndex: 'mainQuantity',
          scopedSlots: { customRender: 'mainQuantity' },
          width: 120,
        },
        {
          title: '主单位',
          dataIndex: 'meUnit',
          width: 100,
          scopedSlots: { customRender: 'meUnit' },
        },
        {
          title: '辅数量',
          dataIndex: 'auxiliaryQuantity',
          width: 100,
        },
        {
          title: '辅单位',
          dataIndex: 'auUnit',
          width: 100,
          scopedSlots: { customRender: 'auUnit' },
        },
        {
          title: 'BOM序号',
          dataIndex: 'number',
          scopedSlots: { customRender: 'number' },
          width: 100,
        },
        {
          title: '配方号',
          dataIndex: 'formulaNo',
          width: 100,
        },
        {
          title: 'BOM版本号',
          dataIndex: 'formulaYear',
          width: 100,
        },
        {
          title: 'BOM编码',
          dataIndex: 'formulaCode',
          width: 100,
        },
        {
          title: 'BOM名称',
          dataIndex: 'formulaName',
          width: 100,
        },
        {
          title: '库存',
          dataIndex: 'stockQuantity',
          width: 100,
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: 120,
          fixed: 'right',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      materialColumns: [
        {
          title: '物料名称',
          dataIndex: 'materialName',
          width: 100,
        },
        {
          title: '规格',
          dataIndex: 'materialSpec',
          width: 80,
        },
        {
          title: '是否客户自带料',
          dataIndex: 'isClientOwn',
          width: 100,
        },
        {
          title: 'BOM比例%',
          dataIndex: 'formula',
          // scopedSlots: { customRender: 'formularRatio' },
          width: 100,
        },
        {
          title: '实际数量',
          dataIndex: 'actualQuantity',
          width: 100,
        },
        {
          title: '含税单价',
          dataIndex: 'taxPrice',
          scopedSlots: { customRender: 'taxPrice' },
          width: 100,
        },
        {
          title: '不含税单价',
          dataIndex: 'noTaxPrice',
          width: 100,
        },
        {
          title: '金额',
          dataIndex: 'price',
          width: 100,
        },
      ],
      packageColumns: [
        {
          title: '包材编号',
          dataIndex: 'packageCode',
          key: 'packageCode',
        },
        {
          title: '包材名称',
          dataIndex: 'packageName',
          key: 'packageName',
        },
        {
          title: '是否自带',
          dataIndex: 'isBrought',
          key: 'isBrought',
          type: JVXETypes.select,
          options: [
            // 下拉选项
            { title: '是', value: '1' },
            { title: '否', value: '0' },
          ],
        },
        {
          title: '规格型号',
          dataIndex: 'noneSpec',
          key: 'noneSpec',
        },
        {
          title: '包材类别',
          dataIndex: 'packageInOutType',
          key: 'packageInOutType',
          type: JVXETypes.select,
          dictCode: 'package_type',
        },
        {
          title: '损耗率(%)',
          dataIndex: 'lossRate',
          key: 'lossRate',
          type: JVXETypes.input,
        },
        {
          title: '比例数量(外包:内包)',
          dataIndex: 'proportion',
          type: JVXETypes.input,
          key: 'proportion',
        },
        {
          title: '材质',
          dataIndex: 'materialQuality',
          key: 'materialQuality',
        },
        {
          title: '尺寸',
          dataIndex: 'size',
          key: 'size',
        },
        {
          title: '包装要求',
          dataIndex: 'requirements',
          key: 'requirements',
          type: JVXETypes.input,
        },
        {
          title: '版样',
          dataIndex: 'patternFile',
          key: 'patternFile',
          type: JVXETypes.file,
          token: true,
        },
        {
          title: '操作',
          key: 'action',
          type: JVXETypes.slot,
          fixed: 'right',
          minWidth: '100px',
          align: 'center',
          slotName: 'action',
        },
      ],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
        style: 'width: 28%;',
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 4 },
        // style: 'width: 15%;',
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
      labelCol24: {
        xs: { span: 24 },
        sm: { span: 24 },
        style: 'width: 100%;',
      },
      wrapperCol24: {
        xs: { span: 24 },
        sm: { span: 24 },
      },
      confirmLoading: false,
      validatorRules: {
        code: [{ required: true, message: '请输入评审表编号!' }],
        currency: [{ required: true, message: '请选择币种!' }],
        flowFlag: [{ required: true, message: '请选择审批流程!' }],
        schedulingNumber: [
          { required: true, message: '请填写销售订单号！（如果是补单，请填写销售订单号；如果是新单，请填写无）!' },
        ],
      },
      url: {
        add: '/review/bussContractRequirementReview/add',
        edit: '/review/bussContractRequirementReview/edit',
        queryById: '/review/bussContractRequirementReview/queryById',
        productByReviewId: '/review/bussContractRequirementReview/reviewProduct/ByReviewId',
        productByIds: '/review/bussContractRequirementReview/reviewProduct/ids',
        bussContractReviewDesFiles: {
          list: '/business/bussContractReviewDes/queryBussContractReviewDesFilesByMainId',
        },
        contractReviewPatterns: {
          list: '/contract.pattern/tslContractReviewPattern/list',
          add: '/contract.pattern/tslContractReviewPattern/add',
          edit: '/contract.pattern/tslContractReviewPattern/edit',
          delete: '/contract.pattern/tslContractReviewPattern/delete',
          model: '/pattern/erpGoodsPattern/detail',
        },
        queryFormularDetailList: '/contract/review/tslContractReviewGoodsFomular/queryByFormularId',
      },
      openDictOptions: {},
      unitDictOptions: {},
      zlunitDictOptions: {},
      patternDictOptions: {},
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    console.log('this.customFormData=', this.customFormData)
    if (this.customFormData != null && this.customFormData.id) {
      this.model = this.customFormData
      this.model.packageList=[]
      this.edit(this.customFormData)
    }
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    this.initDictConfig()
    //this.editAfter() //现在子表内容需要
  },
  mounted() {
    if (this.model.id) {
      this.$refs.outletquote.getFormData(this.model.id)
      if (this.model.currency) {
        this.$refs.outletquote.getLimit(this.model.currency)
      }
      this.checkTaskDisabled(this.model.taskName)
    }
  },
  methods: {
    handlePreviewFile(row) {
      console.log(row, '版样文件')
      FilePreview(row.patternFile)
    },
    formularOk(data) {
      console.log('关联BOM', data)
      if (data && data.id) {
        getAction(this.url.queryFormularDetailList, { id: data.id }).then((res) => {
          console.log('BOM获取结果：', res)
          if (res.success) {
            this.formularDetailList = res.result.map((item) => {
              item.productId = this.selectedProduct.goodsId
              item.reviewId = this.model.id
              item.rowNo = randomUUID()
              return item
            })
            const dataSource = [...this.model.erpGoodsPackageList]
            const target = dataSource.find((item) => item.goodsId === this.selectedProduct.goodsId)
            target.formulaId = data.id
            target.formulaCode = data.code
            target.formulaName = data.name
            target.formulaNo = data.no
            target.formularVos = [...this.formularDetailList]
            this.model.erpGoodsPackageList = dataSource
            console.log('关联BOM后产品数据', this.model.erpGoodsPackageList)
            this.deepCopyGoodsList(this.model.erpGoodsPackageList)
          }
        })
      }
    },
    conFormular() {
      console.log(this.selectedProduct, '选择的产品')
      let good = {
        id: this.selectedProduct.goodsId,
        code: this.selectedProduct.packageCode,
        name: this.selectedProduct.packageName,
      }
      this.$refs.formularCon.add([good])
      this.$refs.formularCon.title = '关联BOM'
      this.$refs.formularCon.disableSubmit = false
    },
    checkTaskDisabled(taskName) {
      console.log(taskName, 'taskName')
      if (taskName) {
        this.disableSubmit = false
        if (taskName == '张顺欣' || taskName == '关联配方') {
          this.formularConDisabled = false
          //视比重必填
          this.validatorRules = {
            proportion: [{ required: true, message: '请输入视比重!' }],
          }
        } else if (taskName == '配方校验' || taskName == '梁明坤') {
          this.formularEditDisabled = false
          this.validatorRules = {
            proportion: [{ required: true, message: '请输入视比重!' }],
            isIncrease: [{ required: true, message: '是否增加费用不能为空!' }],
          }
        } else if (taskName == '质量管理' || taskName == '王淑保') {
          this.qualityCheckDisabled = false
        } else if (taskName == '生产' || taskName == '王吉信' || taskName == '赵勇') {
          this.productDisabled = false
        } else if (taskName == '包材核价' || taskName == '毕翠霞') {
          this.packageDisabled = false
        } else if (taskName.indexOf('原料核价') >-1 || taskName == '张业民') {
          this.purchaseDisabled = false
        } else if (taskName == '业务员最后更改') {
          this.starterDisabled = false
        }
        this.$refs.outletquote.checkTaskDisabled(taskName)
      }
    },
    changeCurrency(val) {
      console.log(val, '修改币种')
      this.$refs.outletquote.getLimit(this.model.currency)
    },
    handlePreviewReviewDesFiles(row) {
      console.log(row)
      if (row && row.filePath) {
        FilePreview(row.filePath.split('_')[0])
      }
    },
    initDictConfig() {
      initDictOptions('package_type').then((res) => {
        console.log(res)
        if (res.success) {
          console.log(res.result)
          this.packageTypeOptions = res.result
        }
      })
      initDictOptions('yes_no').then((res) => {
        console.log(res)
        if (res.success) {
          console.log(res.result)
          this.openDictOptions = res.result
        }
      })
      //初始化字典 - 主单位
      initDictOptions('ji_unit').then((res) => {
        var unitDictOptions = this.unitDictOptions
        console.log(res)
        if (res.success) {
          res.result.forEach(function (item, index) {
            unitDictOptions[item.value] = item.label
          })
        }
        this.unitDictOptions = unitDictOptions
      })
      //初始化字典 - 辅单位
      initDictOptions('zl_unit').then((res) => {
        var zlunitDictOptions = this.zlunitDictOptions
        console.log(res)
        if (res.success) {
          res.result.forEach(function (item, index) {
            zlunitDictOptions[item.value] = item.label
          })
        }
        this.zlunitDictOptions = zlunitDictOptions
      })
      //初始化字典 --配置项
      initDictOptions('tsl_config').then((res) => {
        if (res.success) {
          console.log(res.result)
          let item = res.result.filter((t) => t['text'] == '原材料税率')
          if (item && item.length > 0) {
            console.log(item, '获取原材料税率：', item[0]['value'])
            this.tax = Number.parseFloat(item[0]['value'])
          }
        }
      })
      //初始化字典 - 是否有版样
      this.patternDictOptions = {
        1: '是',
        0: '否',
      }
    },
    tabsChange(activeKey) {
      this.showPatternFlag = false
      if (this.isAdd) {
        this.activeKey = '1'
        this.tabs.activeKey = 1
        return
      }
      this.activeKey = activeKey
      this.tabs.activeKey = activeKey
    },
    getPfCode() {
      postAction('/sys/fillRule/executeRuleByCode/contract_review_code', {}).then((res) => {
        this.model.code = res.result
        this.$forceUpdate()
      })
    },
    getSchedulingNumber() {
      let autoCodeUrl = '/sys/fillRule/executeRuleByCode/'
      if (this.model.desFlowType == 2) {
        autoCodeUrl += 'sales_order_code_international'
      } else {
        autoCodeUrl += 'sales_order_code_domestic'
      }
      postAction(autoCodeUrl, {}).then((res) => {
        this.model.schedulingNumber = res.result
        this.$forceUpdate()
      })
    },
    add(rows) {
      this.contract = rows[0]
      var record = {}
      console.log(rows[0], 'rows[0]')
      Vue.set(record, 'desId', this.contract.id)
      Vue.set(record, 'contractCode', this.contract.code)
      Vue.set(record, 'customerId', this.contract.customerId)
      Vue.set(record, 'customer', this.contract.customer)
      Vue.set(record, 'weight', this.contract.weight)
      Vue.set(record, 'weightUnit', this.contract.weightUnit)
      Vue.set(record, 'payMethod', this.contract.payMethod)
      Vue.set(record, 'deliveryTime', this.contract.deliveryTime)
      Vue.set(record, 'contractTime', this.contract.createTime)
      Vue.set(record, 'formulaReq', this.contract.formulaReq)
      Vue.set(record, 'packReq', this.contract.packReq)
      Vue.set(record, 'erpGoodsPackageList', [])
      Vue.set(record, 'reviewGoodsFomularList', [])
      Vue.set(record, 'packageList', [])
      this.model = Object.assign({}, record)
      console.log(this.model, 'this.model')
      this.getPfCode()
      this.bussContractReviewDesFilesTable.dataSource = []
      let params = { id: this.contract.id }
      this.requestSubTableData(this.url.bussContractReviewDesFiles.list, params, this.bussContractReviewDesFilesTable)
      this.isAdd = true
    },
    edit(record) {
      getAction('/business/bussContractReviewDes/queryById', { id: record.desId }).then((res) => {
        console.log(res)
        let records = res.result
        if (records != null) {
          Vue.set(record, 'contractCode', records.code)
          Vue.set(record, 'customerId', records.customerId)
          Vue.set(record, 'customer', records.customer)
          Vue.set(record, 'weight', records.weight)
          Vue.set(record, 'weightUnit', records.weightUnit)
          Vue.set(record, 'payMethod', records.payMethod)
          Vue.set(record, 'deliveryTime', records.deliveryTime)
          Vue.set(record, 'contractTime', records.createTime)
          Vue.set(record, 'formulaReq', records.formulaReq)
          Vue.set(record, 'packReq', records.packReq)
          Vue.set(record, 'erpGoodsPackageList', [])
          Vue.set(record, 'reviewGoodsFomularList', [])
          Vue.set(record, 'packageList', [])
        }
        this.model = Object.assign({}, record)
        //此处可调用出口业务报价单edit，传入出口业务报价单model
        this.visible = true

        this.editAfter()
      })
    },
    editAfter() {
      let _this = this
      console.log(this.model.id, 'modelId', this.model)
      getAction(this.url.productByReviewId, { id: this.model.id }).then((res) => {
        let erpGoodsList = res.result
        erpGoodsList.forEach(function (item, index) {
          console.log(item, index, '获取评审表关联物料')
          let detail = {}
          detail.goodsId = item.id
          detail.rowKey = item.id
          detail.packageCode = item.code
          detail.packageName = item.name
          detail.coRate = item.coRate
          detail.noneSpec = item.noneSpec
          detail.meUnit = item.meUnit
          detail.auUnit = item.auUnit
          detail.formulaId = item.formulaId
          detail.formulaCode = item.formulaCode
          detail.formulaName = item.formulaName
          detail.formulaYear = item.formulaYear
          detail.packageType = item.packageType
          detail.packageVos = item.packageVos
          detail.formularVos = item.formularVos.map((item) => {
            return { ...item, rowNo: item.id }
          })
          detail.number = item.number
          detail.mainQuantity = item.mainQuantity
          detail.auxiliaryQuantity = item.auxiliaryQuantity
          detail.isProduction = item.isProduction
          // _this.filterPackageId(item.id);
          _this.model.erpGoodsPackageList.push(detail)
        })

        if (_this.model.erpGoodsPackageList == null) {
          _this.model.erpGoodsPackageList = []
          _this.isTotalAmountOk = false
          _this.model.totalProductAmount = 0
        } else {
          _this.checkIsTotalAmountOk()
          _this.deepCopyGoodsList(_this.model.erpGoodsPackageList)
          _this.selectedRowKeys = _this.model.erpGoodsPackageList.map((item) => item.rowKey)
          _this.onSelectChange(_this.selectedRowKeys, _this.model.erpGoodsPackageList)
        }
      })

      this.bussContractReviewDesFilesTable.dataSource = []
      let params = { id: this.model.desId }
      this.requestSubTableData(this.url.bussContractReviewDesFiles.list, params, this.bussContractReviewDesFilesTable)

      console.log(_this.model.erpGoodsPackageList, '_this.model.erpGoodsPackageList')
    },
    getMyEvent() {
      const that = this
      that.$emit('ok')
    },
    submitAll() {
      if (!this.isTotalAmountOk) {
        this.$message.warning('辅数量合计超出订货数量1%！请先修改！')
        return
      }

      this.$refs.outletquote.submitForm(this.model.id)
      const that = this
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = this.url.edit
          let method = 'put'
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                this.isAdd = false
                this.model.id = res.message
                that.$message.success(res.message)
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    submitForm() {
      //提交
      const that = this
      console.log(this.tabs)
      if (!this.disableSubmit) {
        this.submitAll()
        return
      }
      if (this.tabs.activeKey == 1 && this.model.id) {
        this.activeKey = '2'
        this.tabs.activeKey = 2
        return
      }
      if (this.tabs.activeKey == 2 && !this.isTotalAmountOk) {
        that.$message.warning('辅数量合计超出订货数量1%！请先修改！')
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          console.log(this.model, 'submitForm')
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                // that.$message.success(res.message);
                this.isAdd = false
                this.model.id = res.message
                if (this.tabs.activeKey == 1) {
                  this.activeKey = '2'
                  this.tabs.activeKey = 2
                  return
                }
                if (this.tabs.activeKey == 2) {
                  this.model.id = res.message
                  this.activeKey = '3'
                  this.tabs.activeKey = 3
                  this.$refs.outletquote.getFormData(this.model.id)
                  return
                }
                if (this.tabs.activeKey == 3) {
                  this.$refs.outletquote.submitForm(this.model.id)
                  return
                  // that.$emit('ok');
                }
                // that.$emit('ok');
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    addGoods: function () {
      // 新增物料
      // console.log(this.$refs.selectGoodsList)
      this.$nextTick(() => {
        this.$refs.selectGoodsList.add()
      })
      // this.$refs.selectGoodsList.add();
      // this.$refs.selectGoodsList.title = "新增";
      // this.$refs.selectGoodsList.disableSubmit = false;
    },
    goodsOk(datas) {
      let _this = this
      postAction(this.url.productByIds, { ids: datas }).then((res) => {
        let erpGoodsList = res.result
        const gids = _this.model.erpGoodsPackageList.map((item) => item.goodsId)
        console.log(res.result, gids, '新增物料')
        erpGoodsList.forEach(function (item, index) {
          console.log(item, index)
          if (gids.indexOf(item.id) > -1) {
            console.log('选择重复物料！', item.id)
            return
          }
          let detail = {}
          detail.goodsId = item.id
          detail.rowKey = item.id
          detail.packageCode = item.code
          detail.packageName = item.name
          detail.noneSpec = item.noneSpec
          detail.coRate = item.coRate
          detail.meUnit = item.meUnit
          detail.auUnit = item.auUnit
          detail.formulaId = item.formulaId
          detail.formulaCode = item.formulaCode
          detail.formulaName = item.formulaName
          detail.formulaYear = item.formulaYear
          detail.packageType = item.packageType
          detail.packageVos = item.packageVos
          detail.formularVos = []
          if (item.formularVos && item.formularVos.length > 0) {
            item.formularVos.forEach((fitem, findex) => {
              fitem.reviewId = _this.model.id
              fitem.rowNo = fitem.id
              detail.formularVos.push(fitem)
            })
            console.log(detail.formularVos)
          }
          // _this.filterPackageId(item.id);
          _this.model.erpGoodsPackageList.push(detail)
        })
        _this.deepCopyGoodsList(_this.model.erpGoodsPackageList)
      })
    },
    getGoodsById(id) {
      let _this = this
      let ids = []
      ids.push(id)
      postAction(this.url.productByIds, { ids: ids }).then((res) => {
        let erpGoods = res.result[0]
        const dataSource = [..._this.model.erpGoodsPackageList]
        let record = dataSource.find((item) => item.goodsId == id)
        console.log(res.result, erpGoods, record, '获取物料')
        record.packageVos = [...erpGoods.packageVos]
        record.formularVos = []
        if (erpGoods.formularVos && erpGoods.formularVos.length > 0) {
          record.formularVos = erpGoods.formularVos.map((item) => {
            return { ...item, rowNo: item.materialId + Math.random() }
          })
        }
        _this.model.packageList = record.packageVos
        _this.formularDetailList = record.formularVos
        _this.model.erpGoodsPackageList = dataSource
        //_this.onSelectChange(_this.selectedRowKeys, _this.model.erpGoodsPackageList)
        _this.deepCopyGoodsList(dataSource)
      })
    },
    packageOk(datas) {
      console.log(datas, this.selectedProduct)
      this.model.packageList = []

      // let packageVos = []
      // if (this.selectedProduct.packageVos && this.selectedProduct.packageVos.length > 0) {
      //   packageVos = this.selectedProduct.packageVos
      // }
      let _this = this
      postAction(this.url.productByIds, { ids: datas }).then((res) => {
        let resVos = res.result
        console.log(res.result, '新增包材')
        if (resVos && resVos.length > 0) {
          resVos.forEach((item) => {
            let packageObj = {}
            packageObj.goodsId = _this.selectedProduct.goodsId
            packageObj.packageId = item.id
            packageObj.packageCode = item.code
            packageObj.packageName = item.name
            packageObj.noneSpec = item.noneSpec
            packageObj.packSpec = item.packSpec
            packageObj.size = item.size
            packageObj.materialQuality = item.materialQuality
            packageObj.detailNo = item.id + Math.random()
            packageObj.requirements = item.packRequire
            packageObj.isPattern = item.isPattern
            packageObj.proportion = item.proportion

            packageObj.isBrought = 0
            this.selectedProduct.packageVos.push(packageObj)
          })
          // this.selectedProduct.packageVos = packageVos
          this.model.packageList = [...this.selectedProduct.packageVos]
          console.log('新增包材', this.selectedProduct, this.model.packageList)
          _this.deepCopyGoodsList(_this.model.erpGoodsPackageList)
          _this.$forceUpdate()
        }
      })
    },
    addPackage() {
      if (this.selectedRows.length < 1) {
        this.$message.error('请先选择产品')
        return
      }

      // 新增物料
      // console.log(this.$refs.selectGoodsList)
      this.$nextTick(() => {
        this.$refs.selectPackageList.add()
      })
    },
    filterPackageId(goodsId) {
      this.model.erpGoodsPackageList = this.model.erpGoodsPackageList.filter(function (item) {
        return item.goodsId !== goodsId
      })
    },
    onCellChange(record, dataIndex, value) {
      console.log(this.model.erpGoodsPackageList)
      console.log(record)
      const dataSource = [...this.model.erpGoodsPackageList]
      const target = dataSource.find((item) => item.packageCode === record.packageCode)
      // console.log(target,key,dataIndex,value)
      if (record) {
        target[dataIndex] = value
        console.log('isProduction', value, this.erpPackageListTmp)
        if (dataIndex == 'isProduction') {
          //生产
          if (value == '1') {
            const tmpTarget = this.erpPackageListTmp.find((item) => item.packageCode === record.packageCode)
            console.log(tmpTarget, 'tmpTarget')
            if (tmpTarget.formularVos && tmpTarget.formularVos.length > 0) {
              this.formularDetailList = tmpTarget.formularVos
              target.formularVos = [...tmpTarget.formularVos]
              this.model.packageList = tmpTarget.packageVos
              target.packageVos = [...tmpTarget.packageVos]
              this.model.erpGoodsPackageList = dataSource
              this.onSelectChange(target.rowKey, this.model.erpGoodsPackageList)
            } else {
              //获取产品物料关联的数据
              this.getGoodsById(target.goodsId)
            }
          } else {
            //不生产
            this.formularDetailList = []
            this.model.packageList = []
            target.formularVos = []
            target.packageVos = []
            this.model.erpGoodsPackageList = dataSource
          }
        } else {
          this.model.erpGoodsPackageList = dataSource
          this.deepCopyGoodsList(dataSource)
        }
      }
    },
    deepCopyGoodsList(source) {
      this.erpPackageListTmp = []
      if (source && source.length > 0) {
        source.forEach((item) => {
          let target = {}
          target = Object.assign({}, item)
          target.formularVos = []
          if (item.formularVos && item.formularVos.length > 0) {
            item.formularVos.forEach((fitem) => {
              let f = Object.assign({}, fitem)
              target.formularVos.push(f)
            })
          }
          target.packageVos = []
          if (item.packageVos && item.packageVos.length > 0) {
            item.packageVos.forEach((pitem) => {
              let p = Object.assign({}, pitem)
              target.packageVos.push(p)
            })
          }
          this.erpPackageListTmp.push(target)
        })
      }
      console.log(this.erpPackageListTmp, '深度copy')
    },
    onMainQuantityCellChange(record, dataIndex, value) {
      console.log(this.model.erpGoodsPackageList)
      console.log(record)
      const dataSource = [...this.model.erpGoodsPackageList]
      const target = dataSource.find((item) => item.packageCode === record.packageCode)
      // console.log(target,key,dataIndex,value)
      if (record) {
        //修改主数量
        target[dataIndex] = value
        //计算辅数量
        target.auxiliaryQuantity = (Number.parseFloat(target.coRate) * Number.parseFloat(value)).toFixed(6)
        this.model.erpGoodsPackageList = dataSource
        this.deepCopyGoodsList(dataSource)
        this.checkIsTotalAmountOk()
      }
    },
    checkIsTotalAmountOk() {
      if (this.model.erpGoodsPackageList && this.model.erpGoodsPackageList.length > 0) {
        let totalAmount = this.model.erpGoodsPackageList.reduce((sum, item) => {
          return parseFloat(sum) + parseFloat(item.auxiliaryQuantity)
        }, 0)
        this.model.totalProductAmount = Number.parseFloat(totalAmount).toFixed(6)

        if (
          this.model.totalProductAmount > this.model.weight * 1.01 ||
          this.model.totalProductAmount < this.model.weight * (1 - 0.01)
        ) {
          console.log(
            '计算辅数量合计=======',
            this.model.erpGoodsPackageList,
            this.model.totalProductAmount,
            totalAmount
          )
          this.$message.warning('辅数量合计不能超过订货数量的1%！')
          this.isTotalAmountOk = false
        } else {
          this.isTotalAmountOk = true
        }
        this.$forceUpdate()
      } else {
        console.log('没有物料')
        this.model.totalProductAmount = 0
        this.isTotalAmountOk = false
      }
    },
    onFormularCellChange(record, dataIndex, value) {
      console.log('配方修改', record, dataIndex, value, record.productId)
      const dataSource = [...this.model.erpGoodsPackageList]
      const target = dataSource.find((item) => item.goodsId === record.productId)
      const formularSource = target.formularVos
      const formulartarget = formularSource.find((item) => item.rowNo === record.rowNo)
      console.log('查找记录', formulartarget)
      if (record) {
        formulartarget[dataIndex] = value
        if (dataIndex == 'formula') {
          postAction('/base/erpGoodsFormulaDetail/compute/formula', {
            list: formularSource,
            detail: formulartarget,
          }).then((res) => {
            if (res.success) {
              this.$set(formulartarget, 'actualQuantity', res.result)
              formulartarget.noTaxPrice = (Number.parseFloat(formulartarget.taxPrice) / this.tax).toFixed(6)
              formulartarget.price = (
                Number.parseFloat(formulartarget.noTaxPrice) * Number.parseFloat(formulartarget.actualQuantity)
              ).toFixed(2)
              formulartarget.rowNo = formulartarget.rowNo + 1
              this.formularDetailList = formularSource
              console.log('计算完的值', this.formularDetailList)
              this.model.erpGoodsPackageList = dataSource
              console.log('修改后：', this.model.erpGoodsPackageList)
              let materilPrice = this.formularDetailList.reduce((sum, item) => {
                return parseFloat(sum) + parseFloat(item.price)
              }, 0)
              materilPrice = materilPrice ? parseFloat(materilPrice).toFixed(2) : 0
              console.log('原料成本：', materilPrice, record.productId)
              this.$refs.outletquote.calcMaterial(record.productId, materilPrice)
              this.deepCopyGoodsList(dataSource)
            }
          })
        } else {
          formulartarget.noTaxPrice = (Number.parseFloat(formulartarget.taxPrice) / this.tax).toFixed(6)
          formulartarget.price = (
            Number.parseFloat(formulartarget.noTaxPrice) * Number.parseFloat(formulartarget.actualQuantity)
          ).toFixed(2)
          formulartarget.rowNo = formulartarget.rowNo + 1
          this.formularDetailList = formularSource
          console.log('计算完的值', this.formularDetailList)
          this.model.erpGoodsPackageList = dataSource
          console.log('修改后：', this.model.erpGoodsPackageList)
          let materilPrice = this.formularDetailList.reduce((sum, item) => {
            return parseFloat(sum) + parseFloat(item.price)
          }, 0)
          materilPrice = materilPrice ? parseFloat(materilPrice).toFixed(2) : 0
          console.log('原料成本：', materilPrice, record.productId)
          this.$refs.outletquote.calcMaterial(record.productId, materilPrice)
          this.deepCopyGoodsList(dataSource)
        }
      }
    },
    onChildCellChange(record, dataIndex, value) {
      console.log('关联包材修改')
      console.log(this.model.erpGoodsPackageList, this.selectedRows[0])
      console.log(record, dataIndex, value)
      const dataSource = [...this.model.erpGoodsPackageList]
      const target = dataSource.find((item) => item.goodsId === this.selectedRows[0].goodsId)

      const packageSource = target.packageVos
      const packagetarget = packageSource.find((item) => item.packageCode === record.packageCode)
      // console.log(target,key,dataIndex,value)
      if (record) {
        packagetarget[dataIndex] = value
        this.model.packageList = packageSource
        this.model.erpGoodsPackageList = dataSource
        this.deepCopyGoodsList(dataSource)
      }
      console.log(this.model.erpGoodsPackageList)
    },
    onDelete(key) {
      const dataSource = [...this.model.erpGoodsPackageList]
      this.model.erpGoodsPackageList = dataSource.filter((item) => item.goodsId !== key)
      this.model.packageList = []
      this.formularDetailList = []
      this.deepCopyGoodsList(this.model.erpGoodsPackageList)
      this.checkIsTotalAmountOk()
    },
    onDeletePackage(record) {
      const dataSource = [...this.selectedProduct.packageVos]
      this.selectedProduct.packageVos = dataSource.filter((item) => item.detailNo !== record.detailNo)
      this.model.packageList = this.selectedProduct.packageVos
      console.log(this.model.erpGoodsPackageList, this.selectedProduct.packageVos, this.model.packageList)
      this.deepCopyGoodsList(this.model.erpGoodsPackageList)
      this.$forceUpdate()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      if (this.selectedRows.length > 0 && this.selectedRows[0] != null) {
        const key = 'goodsId'
        this.selectedRowKeys = [selectedRowKeys.filter((item) => item !== this.selectedRowKeys[0])[0]]
        this.selectedRows = [selectedRows.filter((item) => item[key] !== this.selectedRows[0][key])[0]]
      } else {
        this.selectedRowKeys = [selectedRowKeys[0]]
        this.selectedRows = [selectedRows[0]]
      }
      this.showPatternFlag = false
      console.log(this.selectedRows, 'this.selectedRows')

      if (this.selectedRows[0] != null) {
        this.selectedProduct = this.selectedRows[0]
        const dataSource = [...this.model.erpGoodsPackageList]
        const target = dataSource.find((item) => item.goodsId === this.selectedRows[0].goodsId)
        console.log('target', target)
        console.log('this.selectedProduct', this.selectedProduct)
        //关联物料包材信息
        if (!this.selectedProduct.packageVos || this.selectedProduct.packageVos.length == 0) {
          this.selectedProduct.packageVos = []

          if (target.packageVos != null && target.packageVos.length > 0) {
            this.model.packageList = target.packageVos
          } else {
            this.model.packageList = []
          }
          this.selectedProduct.packageVos = this.model.packageList
        } else {
          this.model.packageList = this.selectedProduct.packageVos
        }
        if (!this.selectedProduct.packageVos || this.selectedProduct.packageVos.length == 0) {
          this.selectedProduct.packageVos = []

          if (target.packageVos != null && target.packageVos.length > 0) {
            this.model.packageList = target.packageVos
          } else {
            this.model.packageList = []
          }
          this.selectedProduct.packageVos = this.model.packageList
        } else {
          this.model.packageList = this.selectedProduct.packageVos
        }

        let formularVos = target.formularVos || this.selectedProduct.formularVos
        this.formularDetailList = []
        if (formularVos && formularVos.length > 0) {
          formularVos.forEach((fitem, index) => {
            let fdetail = {}
            fdetail.rowNo = fitem.id
            fdetail.materialId = fitem.materialId
            fdetail.materialName = fitem.materialName
            fdetail.materialSpec = fitem.materialSpec
            fdetail.id = fitem.id
            fdetail.productId = fitem.productId
            fdetail.formulaId = fitem.formulaId
            fdetail.isClientOwn = fitem.isClientOwn
            fdetail.actualQuantity = fitem.actualQuantity
            fdetail.computingFormula = fitem.computingFormula
            fdetail.formula = fitem.formula
            fdetail.taxPrice = fitem.taxPrice
            fdetail.noTaxPrice = fitem.noTaxPrice
            fdetail.price = fitem.price
            this.formularDetailList.push(fdetail)
          })

          console.log('获取物料BOM：', this.formularDetailList)
        }
      }
    },
    handleCorrelation(record) {
      this.goodsId = record.goodsId
      this.$refs.selectFormulaList.add()
      this.$refs.selectFormulaList.title = '选择配方'
      this.$refs.selectFormulaList.disableSubmit = false
    },
    formulasOk(datas) {
      console.log(datas)
      const dataSource = [...this.model.erpGoodsPackageList]
      const target = dataSource.find((item) => item.goodsId === this.goodsId)
      if (target) {
        target['formulaId'] = datas.id
        target['formulaYear'] = datas.year
        target['formulaName'] = datas.name
        target['formulaCode'] = datas.code
        // target['formulaNo'] = datas.no;
        this.model.erpGoodsPackageList = dataSource
        this.deepCopyGoodsList(dataSource)
      }
      console.log(this.model.erpGoodsPackageList)
    },
    handleEditClosed(event) {
      let { $table, row, column } = event

      let field = column.property
      let cellValue = row[field]
      // 判断单元格值是否被修改
      if ($table.isUpdateByRow(row, field)) {
        // 校验当前行
        $table.validate(row).then((errMap) => {
          // 校验通过
          if (!errMap) {
            console.log('即时保存数据：', row)
            this.savePattern(row)
          }
        })
      }
    },

    handleFileChange(event) {
      const file = event.target.files[0] // 获取文件
      if (file) {
        // 处理文件，例如上传到服务器
        this.uploadFile(file)
      }
    },
    uploadFile(file) {
      // 这里编写文件上传的逻辑
      console.log('Uploading file...', file)
      // 示例中仅打印文件信息，实际应用中需要编写文件上传代码
      const formData = new FormData()
      formData.append('file', file)

      // 使用axios发送文件
      postAction('/sys/common/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })
        .then((response) => {
          console.log('response')
          console.log(response.message)
          let detail = {}
          detail.patternId = this.packageId
          detail.name = response.message
          postAction('/pattern/erpGoodsPattern/addPattern', detail).then((res) => {
            this.$message.success(res.message)
          })
        })
        .catch((error) => {
          console.error(error)
        })
    },
    // addProc(){
    //   if(this.procSelectRows.length>0){
    //     const rows = this.procSelectRows
    //     this.$nextTick(()=>{
    //       this.contract = rows[0];
    //       this.add();
    //     })
    //   }
    // },
  },
}
</script>
<style lang="stylus" scoped>
.mytable >>> .ant-table-thead > tr > th, .ant-table-tbody > tr > td {
    padding: 2px 2px;
    overflow-wrap: break-word;
}
.mytable >>> .ant-table-tbody .ant-table-row td {
    padding-top: 2px;
    padding-bottom: 2px;
  }
  .mytable{
    .ant-table {
      min-height: 200px !important;
    }
  }
  .mycard{
    padding: 2px 2px;
    height:300px;
  }
  .mycard .ant-card-body{
    padding: 2px 2px;
  }
</style>
